package lanou3g.myfirstapp36kr.activity;

import android.annotation.TargetApi;
import android.content.Intent;

import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build.VERSION_CODES;
import android.os.StrictMode;
import android.text.Html;

import android.text.method.LinkMovementMethod;
import android.text.method.ScrollingMovementMethod;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnScrollChangeListener;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;

import org.greenrobot.greendao.query.Query;

import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import it.sephiroth.android.library.picasso.Picasso;
import lanou3g.myfirstapp36kr.MemoryCache;
import lanou3g.myfirstapp36kr.MyImageListener;
import lanou3g.myfirstapp36kr.myvolleysingleton.Colection;
import lanou3g.myfirstapp36kr.myvolleysingleton.ColectionDao;
import lanou3g.myfirstapp36kr.myvolleysingleton.ColectionDao.Properties;
import lanou3g.myfirstapp36kr.R;
import lanou3g.myfirstapp36kr.base.BaseActivity;
import lanou3g.myfirstapp36kr.entity.FragmentNewsDetails;
import lanou3g.myfirstapp36kr.myvolleysingleton.DaoMasterSingleton;
import lanou3g.myfirstapp36kr.myvolleysingleton.VolleySingleton;

/**
 * Created by dllo on 16/8/6.
 */
@TargetApi(VERSION_CODES.M)
public class NewsDetailsActivity extends BaseActivity implements OnClickListener, OnScrollChangeListener, AnimationListener {
    private ImageView imageViewPic;
    private CheckBox imageViewFavorite;
    private TextView textViewAuthor;
    private TextView textViewTitle;
    private TextView textViewTime;
    private TextView textViewContent;
    private SimpleDateFormat dateFormat;
    private Date date;
    private Html.ImageGetter imageGetter;
    private String pictureUrl;
    private String name;
    private String title;
    private String detailsUrl;
    private long publishTime;
    private long id;
    private String columnName;
    private ColectionDao colectionDao;
    private View layoutBar;
    private ScrollView scrollView;
    private int height;
    private boolean mIsTitleHide = false;
    private boolean mIsAnim = false;
    private float lastX = 0;
    private float lastY = 0;


    @Override
    protected int getLayout() {
        return R.layout.activity_news_details;
    }

    @Override
    protected void initView() {


        ShareSDK.initSDK(this);


        imageViewPic = (ImageView) findViewById(R.id.iv_pic);
        textViewAuthor = (TextView) findViewById(R.id.tv_author);
        textViewTitle = (TextView) findViewById(R.id.tv_title);
        textViewTime = (TextView) findViewById(R.id.tv_time);
        textViewContent = (TextView) findViewById(R.id.tv_context);
        findViewById(R.id.iv_back).setOnClickListener(this);
        findViewById(R.id.iv_more).setOnClickListener(this);

        findViewById(R.id.iv_share).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                showShare();
            }
        });

        imageViewFavorite = (CheckBox) findViewById(R.id.iv_favorite);


        layoutBar = findViewById(R.id.bar_title);
        layoutBar.setBackgroundColor(Color.argb(0x5b,0x91,0xfd,0));
        ViewTreeObserver vto = imageViewPic.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                imageViewPic.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                height = imageViewPic.getHeight();
            }
        });


        struct();
        scrollView = (ScrollView) findViewById(R.id.scrollview);
        scrollView.setOnScrollChangeListener(this);
        colectionDao = DaoMasterSingleton.getDaoMasterSingleton().getColectionDao();
        colectionDao.deleteAll();

    }

    @Override
    protected void initData() {

        Intent intent = getIntent();
        pictureUrl = intent.getStringExtra("pictureUrl");
        //if (BuildConfig.DEBUG) Log.d("NewsDetailsActivity====", pictureUrl);
        name = intent.getStringExtra("name");
        //Log.d("+++++",name);
        title = intent.getStringExtra("title");
        id = intent.getLongExtra("Id",-1);
        //Log.d("+++++",id + "");
        columnName = intent.getStringExtra("columnName");
        //if (BuildConfig.DEBUG) Log.d("NewsDetailsActivity====", title);
        detailsUrl = intent.getStringExtra("detailsUrl");
        //if (BuildConfig.DEBUG) Log.d("NewsDetailsActivity===", detailsUrl);

        publishTime = intent.getLongExtra("publishTime", 0);


        // Query 类代表了一个可以被重复执行的查询
        Query query = colectionDao.queryBuilder()
                .where(Properties.Id.eq(id))
                .build();

//      查询结果以 List 返回
      List notes = query.list();
        if (notes == null || notes.size() == 0){
            imageViewFavorite.setChecked(false);
        }else {
            imageViewFavorite.setChecked(true);
        }

        imageViewFavorite.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                if (b){
                    Toast.makeText(NewsDetailsActivity.this, "收藏", Toast.LENGTH_SHORT).show();
                    Colection colection = new Colection(id,pictureUrl,title,name,publishTime,columnName,detailsUrl);
//                    if (id == colectionDao.queryBuilder().list().get())
                        colectionDao.insertOrReplace(colection);
                }else {
                    colectionDao.deleteByKey(id);
                    Toast.makeText(NewsDetailsActivity.this, "移除收藏", Toast.LENGTH_SHORT).show();

                }
            }
        });


        date = new Date(publishTime);
        dateFormat = new SimpleDateFormat("yyyy MM dd hh:mm:ss");
        String time = dateFormat.format(date);
        //Log.d("NewsDetailsActivity", "publishTime:====" + publishTime);
        //Picasso.with(this).load(pictureUrl).into(imageViewPic);
        RequestQueue requestQueue = VolleySingleton.getVolleySingleton().getRequestQueue();
        ImageLoader imageLoader = new ImageLoader(requestQueue,new MemoryCache());
        imageLoader.get(pictureUrl,new MyImageListener(imageViewPic));
        textViewAuthor.setText(name);
        textViewTitle.setText(title);
        textViewTime.setText(time);
        VolleySingleton.addRequest(detailsUrl, FragmentNewsDetails.class, new Response.Listener<FragmentNewsDetails>() {
            @Override
            public void onResponse(FragmentNewsDetails response) {
                String details = response.getData().getContent();

                textViewContent.setMovementMethod(ScrollingMovementMethod.getInstance());// 设置可滚动
                textViewContent.setMovementMethod(LinkMovementMethod.getInstance());//设置超链接可以打开网页
                textViewContent.setText(Html.fromHtml(details,imageGetter,null));
                //textViewContent.setText(Html.fromHtml(details,null,null));

            }
        }, new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.getMessage();

            }
        });


        imageGetter = new Html.ImageGetter() {
            public Drawable getDrawable(String source) {
                Drawable drawable = null;
                URL url;
                try {
                    url = new URL(source);
                    drawable = Drawable.createFromStream(url.openStream(), ""); // 获取网路图片
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
                DisplayMetrics dm = new DisplayMetrics();
                // 获取屏幕信息
                getWindowManager().getDefaultDisplay().getMetrics(dm);
                if (drawable != null){
                    drawable.setBounds(0, 0, dm.widthPixels - 180,
                            (dm.widthPixels - 180) / drawable.getIntrinsicWidth() * drawable.getIntrinsicHeight());
                }

                drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                return drawable;
            }
        };

    }

    public static void struct() {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads().detectDiskWrites().detectNetwork() // or
                // .detectAll()
                // for
                // all
                // detectable
                // problems
                .penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects() // 探测SQLite数据库操作
                .penaltyLog() // 打印logcat
                .penaltyDeath().build());
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_more:
                startActivity(new Intent(NewsDetailsActivity.this,ShareActivity.class));
        }
    }



    @Override
    public void onScrollChange(View view, int x, int y, int oldx, int oldy) {
        //Toast.makeText(this, "lal", Toast.LENGTH_SHORT).show();
        if (y <= height && y >= 0){
            float scale = (float) y / height;
            float alpha = 255 * scale;
            layoutBar.setBackgroundColor(Color.argb((int)alpha,0xfd,0x91,0x5b));
            layoutBar.setVisibility(View.VISIBLE);
        }
        else if (y > height){
            layoutBar.getBackground().setAlpha(255);
            layoutBar.setVisibility(View.GONE);
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        super.dispatchTouchEvent(ev);
        if (mIsAnim){
            return false;
        }
        final int action = ev.getAction();
        float x = ev.getX();
        float y = ev.getY();
        switch (action){
            case MotionEvent.ACTION_DOWN:
                lastY = y;
                lastX = x;
                return false;
            case MotionEvent.ACTION_MOVE:
                float dY = Math.abs(y - lastY);
                float dX = Math.abs(x - lastX);
                boolean down = y > lastY ? true : false;
                lastY = y;
                lastX = x;
                if (dX < 8 && dY > 8 && !mIsTitleHide && !down){
                    Animation anim = AnimationUtils.loadAnimation(NewsDetailsActivity.this,
                            R.anim.push_top_in);
                    anim.setAnimationListener(NewsDetailsActivity.this);
                    layoutBar.startAnimation(anim);
                }else {
                    return false;
                }
                mIsTitleHide = !mIsTitleHide;
                mIsAnim = true;
                break;
            default:
                return false;
        }
        return false;

    }

    @Override
    public void onAnimationStart(Animation animation) {
        //layoutBar.setVisibility(View.VISIBLE);
//        if (mIsTitleHide){
//            FrameLayout.LayoutParams lp = (LayoutParams) scrollView.getLayoutParams();
//            lp.setMargins(0,0,0,0);
//            scrollView.setLayoutParams(lp);
//        }else {
//            FrameLayout.LayoutParams lp = (LayoutParams) layoutBar.getLayoutParams();
//            lp.setMargins(0,0,0,0);
//            layoutBar.setLayoutParams(lp);
//            FrameLayout.LayoutParams lp1 = (LayoutParams) scrollView.getLayoutParams();
//            lp1.setMargins(0,50,0,0);
//            scrollView.setLayoutParams(lp1);
//        }

    }

    @Override
    public void onAnimationEnd(Animation animation) {
//        if (mIsTitleHide){
//            layoutBar.setVisibility(View.GONE);
//        }else {
//
//        }
//        mIsAnim = false;
        //layoutBar.setVisibility(View.VISIBLE);
//
    }

    @Override
    public void onAnimationRepeat(Animation animation) {

    }




    private void showShare() {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间等使用
        oks.setTitle("标题");
        // titleUrl是标题的网络链接，QQ和QQ空间等使用
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("我是分享文本");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");

        // 启动分享GUI
        oks.show(this);
    }
}
